package com.voicechat.firstmet.activity;

import android.Manifest;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.DataSetObserver;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.Layout;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.opensource.svgaplayer.SVGACallback;
import com.opensource.svgaplayer.SVGADrawable;
import com.opensource.svgaplayer.SVGADynamicEntity;
import com.opensource.svgaplayer.SVGAImageView;
import com.opensource.svgaplayer.SVGAParser;
import com.opensource.svgaplayer.SVGAVideoEntity;
import com.tencent.TIMConversationType;
import com.tencent.TIMMessage;
import com.tencent.TIMMessageStatus;
import com.voicechat.firstmet.R;
import com.voicechat.firstmet.base.BaseActivity;
import com.voicechat.firstmet.bean.MySelfInfoBean;
import com.voicechat.firstmet.client.OssConfig;
import com.voicechat.firstmet.client.WsManager;
import com.voicechat.firstmet.fragment.EmojiShowFragment;
import com.voicechat.firstmet.fragment.IMChatSendVoiceFragment;
import com.voicechat.firstmet.fragment.IMSendGifFragment;
import com.voicechat.firstmet.imcontrol.ChatAdapter;
import com.voicechat.firstmet.imcontrol.ChatPresenter;
import com.voicechat.firstmet.imcontrol.ChatView;
import com.voicechat.firstmet.imcontrol.ImageMessage;
import com.voicechat.firstmet.imcontrol.MediaUtil;
import com.voicechat.firstmet.imcontrol.Message;
import com.voicechat.firstmet.imcontrol.MessageFactory;
import com.voicechat.firstmet.imcontrol.RefreshEvent;
import com.voicechat.firstmet.imcontrol.TextMessage;
import com.voicechat.firstmet.imcontrol.VoiceMessage;
import com.voicechat.firstmet.net.HTTPAPI;
import com.voicechat.firstmet.net.service.MeInfoService;
import com.voicechat.firstmet.realm.ListBean;
import com.voicechat.firstmet.utils.CheckAudioPermission;
import com.voicechat.firstmet.utils.ParcelableUtils;
import com.voicechat.firstmet.utils.PhoneUtils;
import com.voicechat.firstmet.utils.PopUtils;
import com.voicechat.firstmet.utils.RecorderUtil;
import com.voicechat.firstmet.utils.SPUtils;
import com.voicechat.firstmet.utils.SoftUtils;
import com.voicechat.firstmet.utils.StatusBarUtils;
import com.voicechat.firstmet.utils.Utils;
import com.voicechat.firstmet.view.EmojiKeyboard;

import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import kotlin.Unit;
import kotlin.jvm.functions.Function1;
import kotlin.jvm.functions.Function2;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * @ProjectName: FirstMet
 * @Package: com.voicechat.firstmet.activity
 * @ClassName: IMChatActivity
 * @Description: 聊天页面
 * @Author: ljp
 * @CreateDate: 2018/11/8 15:21
 * @Version: 1.0
 */
public class IMChatActivity extends BaseActivity implements ChatView {
    @BindView(R.id.linear_back)
    LinearLayout linearBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.recycle_msg_list)
    ListView listView;
    @BindView(R.id.tv_send)
    TextView tvSend;
    @BindView(R.id.frame_layout)
    FrameLayout frameLayout;
    @BindView(R.id.et_content)
    EditText etContent;
    @BindView(R.id.send_voice)
    ImageView sendVoice;
    @BindView(R.id.send_image)
    ImageView sendImage;
    @BindView(R.id.send_gif)
    ImageView sendGif;
    @BindView(R.id.send_voice_chat)
    ImageView sendVoiceCha;
    @BindView(R.id.send_emjoy)
    ImageView sendEmjoy;
    private static String TAG = "IMChatActivity";
    //@BindView(R.id.svgImage)
    SVGAImageView svgImage;
    //private MySelfInfoBean.ObjectBean objectBean;
    private ChatPresenter presenter;
    private ChatAdapter adapter;
    private List<Message> messageList = new ArrayList<>();
    private List<LocalMedia> selectList;
    private IMChatSendVoiceFragment sendVoiceFragment;
    private IMSendGifFragment sendGifFragment;
    private EmojiShowFragment emojiShowFragment;
    private String showFragmentTag;
    private boolean isKoeBordShow;//判断软件盘是否弹出
    private RecorderUtil recorder = new RecorderUtil();
    private String otherId;//对方id
    private EmojiKeyboard emojiKeyboard;
    public static MySelfInfoBean.ObjectBean mySeleInfo;
    public static String token;
    public static String deviceInfo;
    private String name;//对方昵称
    private String isAnchor;//对方是否是主播，1普通用户 2主播
    private String type;//类型标记，搭讪跳转
    private boolean isSvg;//开始播放svg动画
    @Override
    protected int setStatusBarColor() {
        return 0;
    }

    @Override
    protected boolean isSettingStatusBarText() {
        return false;
    }

    @Override
    protected int loadLayout() {
        return R.layout.activity_im_chat;
    }

    @Override
    protected void initLayout(Bundle savedInstanceState) {
        Log.i(TAG, "initLayout: -----getTaskId------"+this.getTaskId());
        ButterKnife.bind(this);
        //透明状态栏
        StatusBarUtils.Full(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            this.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }
        mySeleInfo = MySelfInfoBean.ObjectBean.CREATOR.createFromParcel(ParcelableUtils.unmarshall(
                SPUtils.getEditoString(SPUtils.SP_MYSELFINFO)));
        token = SPUtils.getEditoString(SPUtils.SP_TOKEN);
        deviceInfo = PhoneUtils.getDeviceInfo(context);
        otherId = getIntent().getStringExtra("otherId");
        name = getIntent().getStringExtra("name");
        isAnchor = getIntent().getStringExtra("isAnchor");
        type = getIntent().getStringExtra("type");
        tvTitle.setText(name);
        if (type.equals("accost")) {
            sendGiftAccost();
        }
        initView();
    }
    /**
     * @return
     * @method
     * @description 发送礼物
     * @date: 2018/11/23 12:04
     * @author: ljp
     */
    public void initService(ListBean data) {
        sendReplyMessage();
        MeInfoService.sendGiftChat(mySeleInfo.getId(), token, deviceInfo, otherId, data.getId(), data.getGold() + "",
                "4", "1").subscribe(result -> {
            Log.i(TAG, "onReceive: ----BroadcastManager--result---" + result);
            if (result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS) {
                if (!TextUtils.isEmpty(data.getAnimationUrl())) {
                    try {
                        showPopu(new URL(OssConfig.OSS_HTTP + data.getAnimationUrl()));
                    } catch (MalformedURLException e) {
                        e.printStackTrace();
                    }
                }
                frameLayout.setVisibility(View.GONE);
                toast_MakeText("送礼成功");
            } else if (result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETURN_NO_TOKEN) {
                Utils.setToken(context);
            } else if (result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETURN_NO_GOLD) {
                toast_MakeText(result.getMsg());
            } else {
                toast_MakeText("送礼失败！");
            }
        }, throwable -> {
            Log.i(TAG, "onReceive: -throwable---" + throwable.toString());
        });
        frameLayout.setVisibility(View.GONE);
        //通知服务器回复搭讪消息

    }

    private void showPopu(URL url) {
        isSvg = true;
        View view = View.inflate(context, R.layout.popu_ceishi, null);
        svgImage = view.findViewById(R.id.svgImage);
        PopUtils.showPopupWindowURL(activity, view, false);
        loadAnimation(url);
    }

    public static void navToChat(Context context, String otherId, String name, String isAnchor, String type) {
        Intent intent = new Intent(context, IMChatActivity.class);
        intent.putExtra("otherId", otherId);
        intent.putExtra("name", name);
        intent.putExtra("isAnchor", isAnchor);
        intent.putExtra("type", type);
        //intent.putExtra("type", type);
        context.startActivity(intent);
    }

    /**
     * @return
     * @method
     * @description 搭讪送礼物
     * @date: 2018/12/1 10:43
     * @author: ljp
     */
    private void sendGiftAccost() {
        MeInfoService.sendGiftChat(mySeleInfo.getId(), token, deviceInfo, otherId, "", "", "6", "1").subscribe(result -> {
            Log.i(TAG, "onReceive: ---------" + result);
            if (result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS) {
                toast_MakeText("搭讪成功！");
            } else if (result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETURN_NO_TOKEN) {
                Utils.setToken(context);
            } else if (result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETURN_NO_GOLD) {
                // toast_MakeText(result.getMsg());
                accostFaial(result.getMsg());
            } else {
                //toast_MakeText(result.getMsg());
                accostFaial(result.getMsg());
            }
        }, throwable -> {
            toast_MakeText(getResources().getString(R.string.net_error));
            Log.i(TAG, "onReceive: ----" + throwable.toString());
        });

    }

    //搭讪失败，退出页面
    private void accostFaial(String msg) {
        /* @setIcon 设置对话框图标
         * @setTitle 设置对话框标题
         * @setMessage 设置对话框消息提示
         * setXXX方法返回Dialog对象，因此可以链式设置属性
         */
        final AlertDialog.Builder normalDialog =
                new AlertDialog.Builder(context);
        //normalDialog.setTitle("我是一个普通Dialog");
        normalDialog.setMessage(msg);
        normalDialog.setPositiveButton("充值",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //...To-do
                        Uri uri = Uri.parse(HTTPAPI.URL_RECHARGE + "id=" + mySeleInfo.getNumber());
                        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                        startActivity(intent);
                        dialog.dismiss();
                        finish();
                    }
                });
        normalDialog.setNegativeButton("关闭",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //...To-do
                        dialog.dismiss();
                        finish();
                    }
                });
        // 显示
        normalDialog.show();
    }

    /**
     * @return
     * @method
     * @description 数据控件实力话
     * @date: 2018/11/12 11:18
     * @author: ljp
     */
    private void initView() {
        tvSend.setEnabled(false);
        isKoeBordShow = false;//默认没有弹出
        EmojiShowFragment.setEditMsg(etContent);
        IMSendGifFragment.setSvgaImageView(svgImage);
        //监听软键盘状态
        SoftUtils.doMonitorSoftKeyWord(listView, new SoftUtils.OnSoftKeyWordShowListener() {
            @Override
            public void hasShow(boolean isShow) {
                isKoeBordShow = isShow;
                if (isShow && frameLayout.getVisibility() == View.VISIBLE && etContent.hasFocus()) {
                    frameLayout.setVisibility(View.GONE);
                }
            }
        });
        //判断edittext，是否获得焦点
        etContent.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    if (frameLayout.getVisibility() == View.VISIBLE) {
                        //frameLayout.setVisibility(View.GONE);
                    }
                }
            }
        });
        etContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.toString().trim().length() != 0 && !s.toString().trim().contains("  ")) {
                    tvSend.setEnabled(true);
                    tvSend.setBackgroundResource(R.drawable.login_btn);
                }else {
                    tvSend.setEnabled(false);
                    tvSend.setBackgroundResource(R.drawable.login_btn_2);
                }
            }
            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        presenter = new ChatPresenter(this, otherId, TIMConversationType.C2C);
        adapter = new ChatAdapter(this, R.layout.ietm_message_chat, messageList);
        listView.setAdapter(adapter);
        getTotalHeightofListView(listView);
        listView.setTranscriptMode(ListView.TRANSCRIPT_MODE_NORMAL);
        adapter.registerDataSetObserver(new DataSetObserver() {
            @Override
            public void onChanged() {
                super.onChanged();
                listView.setSelection(adapter.getCount() - 1);
            }
        });
        adapter.setItemSetClick(new ChatAdapter.ItemSetClick() {
            @Override
            public void setItemClick(int position) {
                messageList.get(position).navToPerson(context,otherId);
            }
        });
        listView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        Utils.hideSoftInput(v.getWindowToken(), context);
                        frameLayout.setVisibility(View.GONE);
                        break;
                }
                return false;
            }
        });
        registerForContextMenu(listView);
        listView.setOnScrollListener(new AbsListView.OnScrollListener() {
            private int firstItem;

            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE && firstItem == 0) {
                    //如果拉到顶端读取更多消息
                    presenter.getMessage(messageList.size() > 0 ? messageList.get(0).getMessage() : null);
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                firstItem = firstVisibleItem;
            }
        });
        presenter.start();
    }

    public static int getTotalHeightofListView(ListView listView) {
        ListAdapter mAdapter = listView.getAdapter();
        if (mAdapter == null) {
            return 0;
        }
        int totalHeight = 0;
        for (int i = 0; i < mAdapter.getCount(); i++) {
            View mView = mAdapter.getView(i, null, listView);
            mView.measure(
                    View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                    View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
            //mView.measure(0, 0);
            totalHeight += mView.getMeasuredHeight();
            // LogUtil.d("数据" + i, String.valueOf(totalHeight));
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (mAdapter.getCount() - 1));
        //LogUtil.d("数据", "listview总高度="+ params.height);
        listView.setLayoutParams(params);
        listView.requestLayout();
        return totalHeight;
    }

    @OnClick({R.id.linear_back, R.id.tv_send, R.id.send_voice,
            R.id.send_image, R.id.send_gif, R.id.send_voice_chat, R.id.send_emjoy})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.linear_back:
                finish();
                break;
            case R.id.tv_send://发送文本
                sendText();
                break;
            case R.id.send_voice://发送语音
                if(Build.VERSION.SDK_INT < 23){
                    if(CheckAudioPermission.isHasPermission(context)){
                        setFragment(view, 0);
                    }else {
                        ActivityCompat.requestPermissions(this, new String[]{
                                Manifest.permission.RECORD_AUDIO}, 1);
                    }
                }else {
                    if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO)
                            != PackageManager.PERMISSION_GRANTED) {
                        ActivityCompat.requestPermissions(this, new String[]{
                                Manifest.permission.RECORD_AUDIO}, 1);
                    } else {
                        setFragment(view, 0);
                    }
                }
                break;
            case R.id.send_image://发送图片
                sendImage();
                break;
            case R.id.send_gif://发送礼物
                setFragment(view, 1);
                break;
            case R.id.send_voice_chat://发送语音通话
                judeType();
                break;
            case R.id.send_emjoy://发送表情
                setFragment(view, 2);
                break;
        }
    }

    /**
     * @return
     * @method
     * @description 是主播还是用户判断
     * @date: 2018/11/26 17:53
     * @author: ljp
     */
    private void judeType() {
        if(Build.VERSION.SDK_INT < 23){
            if(CheckAudioPermission.isHasPermission(context)){
                //对方是否是主播，1普通用户 2主播
                Log.i(TAG, "judeType: ----isAnchor-----" + isAnchor);
                //首先判断自己是否是用户
                if (mySeleInfo.getType() == 1) {//1普通用户2主播
                    //然后判断对方是否是用户
                    if (isAnchor.equals("1")) { //对方是否是主播，1普通用户 2主播
                        //弹出金币设置页面
                        showGoldPopu();
                    } else {
                        VoiceChatJude();
                    }
                } else {
                    VoiceChatJude();
                }
            }else {
                ActivityCompat.requestPermissions(this, new String[]{
                        Manifest.permission.RECORD_AUDIO}, 1);
            }
        }else {
            if (ContextCompat.checkSelfPermission(activity, Manifest.permission.RECORD_AUDIO)
                    != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(activity, new String[]{
                        Manifest.permission.RECORD_AUDIO}, 1);
            } else {
                //对方是否是主播，1普通用户 2主播
                Log.i(TAG, "judeType: ----isAnchor-----" + isAnchor);
                //首先判断自己是否是用户
                if (mySeleInfo.getType() == 1) {//1普通用户2主播
                    //然后判断对方是否是用户
                    if (isAnchor.equals("1")) { //对方是否是主播，1普通用户 2主播
                        //弹出金币设置页面
                        showGoldPopu();
                    } else {
                        VoiceChatJude();
                    }
                } else {
                    VoiceChatJude();
                }
            }
        }
    }

    /**
     * @return
     * @method
     * @description 普通用户金币设置
     * @date: 2018/11/26 17:55
     * @author: ljp
     */
    private void showGoldPopu() {
        View view = View.inflate(context, R.layout.popu_gold_layout, null);
        PopUtils.showPopupWindow(activity, view, false);
        ImageView imageClose = view.findViewById(R.id.image_close);
        TextView textView = view.findViewById(R.id.tv_voice_chat);
        imageClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (PopUtils.isPopShowing()) {
                    PopUtils.hidePopupWindow();
                }
            }
        });
        textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                VoiceChatJude();
                PopUtils.hidePopupWindow();
            }
        });
    }

    /**
     * @return
     * @method
     * @description 向对方发起语音通话请求
     * @date: 2018/11/21 12:06
     * @author: ljp
     */
    private void VoiceChatJude() {
        MeInfoService.voiceChatJude(otherId, token = SPUtils.getEditoString(SPUtils.SP_TOKEN), PhoneUtils.getDeviceInfo(context), mySeleInfo.getId()).subscribe(voiceChatBean -> {
            Log.i(TAG, "VoiceChatJude: ---------" + voiceChatBean.getCode());
            Log.i(TAG, "VoiceChatJude: ---------" + voiceChatBean.getMsg());
            //Log.i(TAG, "VoiceChatJude: ---------"+ voiceChatBean.getObject().toString());
            if (voiceChatBean.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETURN_NO_LINE) {//自己下线，重连长链接
                WsManager.getInstance(context).reconnect(mySeleInfo.getId());
                toast_MakeText("请重试！");
            } else if (voiceChatBean.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_FAIL) {
                toast_MakeText(voiceChatBean.getMsg());
            } else if (voiceChatBean.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS) {//用户在线，可以通话
                Intent intent = new Intent(activity, InviteVoiceChatActivity.class);
                Bundle bundle = new Bundle();
               /* bundle.putString("type", "1");
                bundle.putString("flag", "0");*/
                bundle.putInt("roomId", voiceChatBean.getObject().getRoomId());
                bundle.putParcelable("voiceChat", voiceChatBean.getMap().getCalledUser());
                bundle.putParcelable("voiceChatCalling", voiceChatBean.getMap().getCallingUser());
                intent.putExtra("type", "1");
                intent.putExtra("flag", "0");
                intent.putExtra("bundle", bundle);
                activity.startActivity(intent);
            } else if (voiceChatBean.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETURN_NO_TOKEN) {
                Utils.setToken(context);
            } else {
                toast_MakeText(voiceChatBean.getMsg());
            }
        }, throwable -> {
            toast_MakeText(getResources().getString(R.string.net_error));
            Log.i(TAG, "VoiceChatJude: ----------" + throwable.toString());
        });

    }

    private void setFragment(View view, int i) {
        if (isKoeBordShow) {
            Log.i(TAG, "onClick: --键盘显示---");
            Utils.hideSoftInput(view.getWindowToken(), context);
            setTabSelection(i);
            frameLayout.setVisibility(View.VISIBLE);
        } else {
            setTabSelection(i);
            frameLayout.setVisibility(View.VISIBLE);
        }
        if (sendGifFragment != null) {
            sendGifFragment.setMoney();
        }
    }

    @Override
    public void onAttachFragment(Fragment fragment) {//防止反复创建，造成重叠
        super.onAttachFragment(fragment);
        if (fragment instanceof IMChatSendVoiceFragment) {
            sendVoiceFragment = (IMChatSendVoiceFragment) fragment;
        }
        if (fragment instanceof IMSendGifFragment) {
            sendGifFragment = (IMSendGifFragment) fragment;
        }
        if (fragment instanceof EmojiShowFragment) {
            emojiShowFragment = (EmojiShowFragment) fragment;
        }
    }

    /**
     * @return
     * @method
     * @description 隐藏fragment
     * @date: 2018/11/10 17:44
     * @author: ljp
     */
    @Override
    protected void hideFragments(FragmentTransaction transaction) {
        super.hideFragments(transaction);
        if (null != sendVoiceFragment) {
            transaction.hide(sendVoiceFragment);
        }
        if (null != sendGifFragment) {
            transaction.hide(sendGifFragment);
        }
        if (null != emojiShowFragment) {
            transaction.hide(emojiShowFragment);
        }
    }

    /**
     * @return
     * @method
     * @description 显示fragment
     * @date: 2018/11/10 17:44
     * @author: ljp
     */
    @Override
    protected void showFragment(FragmentTransaction transaction, int index) {
        super.showFragment(transaction, index);
        switch (index) {
            case 0:
                showFragmentTag = "IMChatSendVoiceFragment";
                //mainCommIv.setImageResource(R.mipmap.comm);
                // mainCommTv.setTextColor(getResources().getColor(R.color.colorFF3B5E));
                if (sendVoiceFragment == null) {
                    // 如果GogoFragment为空，则创建一个并添加到界面上
                    sendVoiceFragment = new IMChatSendVoiceFragment();
                    transaction.add(R.id.frame_layout, sendVoiceFragment, showFragmentTag);
                } else {
                    if (sendVoiceFragment.isHidden()) {
                        transaction.show(sendVoiceFragment);
                    }
                }
                break;
            case 1:
                showFragmentTag = "IMSendGifFragment";
                //mainCommIv.setImageResource(R.mipmap.comm);
                // mainCommTv.setTextColor(getResources().getColor(R.color.colorFF3B5E));
                if (sendGifFragment == null) {
                    // 如果GogoFragment为空，则创建一个并添加到界面上
                    sendGifFragment = IMSendGifFragment.newInstance(otherId);
                    transaction.add(R.id.frame_layout, sendGifFragment, showFragmentTag);
                } else {
                    if (sendGifFragment.isHidden()) {
                        transaction.show(sendGifFragment);
                    }
                }
                break;
            case 2:
                showFragmentTag = "EmojiShowFragment";
                //mainCommIv.setImageResource(R.mipmap.comm);
                // mainCommTv.setTextColor(getResources().getColor(R.color.colorFF3B5E));
                if (emojiShowFragment == null) {
                    // 如果GogoFragment为空，则创建一个并添加到界面上
                    emojiShowFragment = EmojiShowFragment.newInstance();
                    transaction.add(R.id.frame_layout, emojiShowFragment, showFragmentTag);
                } else {
                    if (emojiShowFragment.isHidden()) {
                        transaction.show(emojiShowFragment);
                    }
                }
                break;
            default:
                break;
        }
    }

    /**
     * @return
     * @method
     * @description 选择图片
     * @date: 2018/11/9 16:30
     * @author: ljp
     */
    private void initPicture() {
        // 进入相册 以下是例子：用不到的api可以不写
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())//全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                .maxSelectNum(9)// 最大图片选择数量 int
                .imageSpanCount(4)// 每行显示个数 int
                .selectionMode(PictureConfig.MULTIPLE)// 多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE
                .previewImage(true)// 是否可预览图片 true or false
                .isCamera(true)// 是否显示拍照按钮 true or false
                .imageFormat(PictureMimeType.PNG)// 拍照保存图片格式后缀,默认jpeg
                .setOutputCameraPath("/CustomPath")// 自定义拍照保存路径,可不填
                //.isGif(true)// 是否显示gif图片 true or false
                .minimumCompressSize(1024)// 小于100kb的图片不压缩
                .synOrAsy(true)//同步true或异步false 压缩 默认同步
                .isDragFrame(false)// 是否可拖动裁剪框(固定)
                .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
    }

    /**
     * @return
     * @method
     * @description 显示消息
     * @date: 2018/11/8 17:39
     * @author: ljp
     */
    @Override
    public void showMessage(TIMMessage message) {
        Log.i(TAG, "showMessage: ----message----");
        if (message == null) {
            adapter.notifyDataSetChanged();
        } else {
            Message mMessage = MessageFactory.getMessage(message);
            if (mMessage != null) {
                /*if (mMessage instanceof CustomMessage ){
                    String messageType = ((CustomMessage) mMessage).getType();
                    switch (messageType){
                        case CustomMessage.Type.CustomMsgGif6:
                            return;
                        case CustomMessage.Type.CustomMsgGif4:
                            if (messageList.size() == 0) {
                                mMessage.setHasTime(null);
                            } else {
                                mMessage.setHasTime(messageList.get(messageList.size() - 1).getMessage());
                            }
                            messageList.add(mMessage);
                            adapter.notifyDataSetChanged();
                            listView.setSelection(adapter.getCount() - 1);
                            break;
                    }
                }else{*/
                if (messageList.size() == 0) {
                    mMessage.setHasTime(null);
                } else {
                    mMessage.setHasTime(messageList.get(messageList.size() - 1).getMessage());
                }
                messageList.add(mMessage);
                adapter.notifyDataSetChanged();
                listView.setSelection(adapter.getCount() - 1);
            }

            // }
        }
    }

    /**
     * 显示消息
     *
     * @param messages
     */
    @Override
    public void showMessage(List<TIMMessage> messages) {
        Log.i(TAG, "showMessage: ----List-----");
        int newMsgNum = 0;
        for (int i = 0; i < messages.size(); ++i) {
            Message mMessage = MessageFactory.getMessage(messages.get(i));
            if (mMessage == null || messages.get(i).status() == TIMMessageStatus.HasDeleted)
                continue;
            /*if (mMessage instanceof CustomMessage && (((CustomMessage) mMessage).getType().equals(CustomMessage.Type.CustomMsgGif6)))
                continue;*/
            ++newMsgNum;
            if (i != messages.size() - 1) {
                mMessage.setHasTime(messages.get(i + 1));
                messageList.add(0, mMessage);
            } else {
                messageList.add(0, mMessage);
            }
        }
        adapter.notifyDataSetChanged();
        listView.setSelection(newMsgNum);
    }

    /**
     * 清除所有消息，等待刷新
     */
    @Override
    public void clearAllMessage() {
        messageList.clear();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片、视频、音频选择结果回调
                    selectList = PictureSelector.obtainMultipleResult(data);
                    Log.i(TAG, "onActivityResult: -----" + selectList.size());
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true  注意：音视频除外
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true  注意：音视频除外
                    // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
                    // tlist.clear();
                    //tlist.addAll(selectList);
                    for (int i = 0; i < selectList.size(); i++) {
                        String path = selectList.get(i).getPath();
                        File file = new File(path);
                        if (file.exists() && file.length() > 0) {
                            if (file.length() > 1024 * 1024 * 10) {
                                Toast.makeText(this, getString(R.string.chat_file_too_large), Toast.LENGTH_SHORT).show();
                            } else {
                                //通知服务器回复搭讪消息
                                sendReplyMessage();
                                Message message = new ImageMessage(path, true);
                                presenter.sendMessage(message.getMessage());
                            }
                        } else {
                            Toast.makeText(this, getString(R.string.chat_file_not_exist), Toast.LENGTH_SHORT).show();
                        }
                    }
                    break;
            }
        }
    }

    /**
     * 发送消息成功
     *
     * @param message 返回的消息
     */
    @Override
    public void onSendMessageSuccess(TIMMessage message) {
        // Log.i(TAG, "onSendMessageSuccess: ----"+message.toString());
        showMessage(message);
    }

    @Override
    public void onSendMessageFail(int code, String desc, TIMMessage message) {
        // Log.i(TAG, "onSendMessageFail: ----"+message.getMessageLocator()+"---"+code);

    }

    @Override
    public void onBackPressed() {
        //if (isSvg) {
            if( PopUtils.isPopShowing()){
               // PopUtils.hidePopupWindow();
                return ;
            }
       // }
        super.onBackPressed();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK ) { //按下的如果是BACK，同时没有重复
           // if (isSvg) {
                if( PopUtils.isPopShowing()){
                  //  PopUtils.hidePopupWindow();
                    return true ;
                }
          //  }
        }
        return super.onKeyDown(keyCode,event);
    }

    /**
     * @return
     * @method
     * @description 发送图片
     * @date: 2018/11/9 16:30
     * @author: ljp
     */
    @Override
    public void sendImage() {
        initPicture();
    }

    @Override
    public void sendPhoto() {

    }

    /**
     * @return
     * @method
     * @description 发送文本消息
     * @date: 2018/11/8 16:49
     * @author: ljp
     */
    @Override
    public void sendText() {
        sendReplyMessage();
        Message message = new TextMessage(etContent.getText());
        presenter.sendMessage(message.getMessage());
        etContent.setText("");
        //通知服务器回复搭讪消息

    }

    /**
     * @return
     * @method
     * @description 开始发送语音消息
     * @date: 2018/11/10 15:14
     * @author: ljp
     */
    @Override
    public void startSendVoice() {
        recorder.startRecording();
    }

    /**
     * @return
     * @method
     * @description 监听录音状态
     * @date: 2018/11/10 15:14
     * @author: ljp
     */
    public RecorderUtil getRecorder() {
        return recorder;
    }

    /**
     * @return
     * @method
     * @description 结束发送语音消息
     * @date: 2018/11/10 15:14
     * @author: ljp
     */
    @Override
    public void endSendVoice() {
        recorder.stopRecording();
        if (recorder.getTimeInterval() < 1) {
            Toast.makeText(this, getResources().getString(R.string.chat_audio_too_short), Toast.LENGTH_SHORT).show();
        } else {
            Message message = new VoiceMessage(recorder.getTimeInterval(), recorder.getFilePath());
            //通知服务器回复搭讪消息
            sendReplyMessage();
            presenter.sendMessage(message.getMessage());
        }
    }

    /**
     * @return
     * @method
     * @description 取消发送录音
     * @date: 2018/11/10 15:14
     * @author: ljp
     */
    public void cacalSendVoice() {
        recorder.stopRecording();
    }

    /**
     * 清除所有消息，等待刷新
     */
    @Override
    public void cancelSendVoice() {
        messageList.clear();
    }

    /**
     * 正在发送
     */
    @Override
    public void sending() {
        // Message message = new CustomMessage(CustomMessage.Type.TYPING);
        // presenter.sendOnlineMessage(message.getMessage());
    }

    /**
     * @return
     * @method
     * @description 发送语音邀请消息
     * @date: 2018/11/12 16:23
     * @author: ljp
     */
    @Override
    public void sendCustomVoiceChat() {
        /*String trim = etContent.getText().toString().trim();
        CustomMessage customMessage = new CustomMessage(message.getMessage());
        Intent intent = new Intent(App.getContext(), InviteVoiceChatActivity.class);
        intent.putExtra("type", "1");
        intent.putExtra("result", customMessage);
        startActivity(intent);*/
    }

    /**
     * @return
     * @method
     * @description 发送语音接听消息
     * @date: 2018/11/12 16:23
     * @author: ljp
     */
    @Override
    public void sendCustomVoiceChatAnswer(String trim) {
       /* CustomMessage customMessage = new CustomMessage(message.getMessage());
        Intent intent = new Intent(App.getContext(), InviteVoiceChatActivity.class);
        intent.putExtra("type","1");
        intent.putExtra("result",customMessage);
        startActivity(intent);*/
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        MediaUtil.getInstance().stop();
        presenter.stop();
    }

    @Override
    protected void onPause() {
        super.onPause();
        RefreshEvent.getInstance().onRefresh();
        presenter.readMessages();
        MediaUtil.getInstance().stop();
    }

    /**
     * ⑨重写onRequestPermissionsResult方法
     * 获取动态权限请求的结果,再开启录制音频
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            // setFragment(sendVoice, 0);
        } else {
            Toast.makeText(this, "用户拒绝了权限,请先去设置中打开录音权限", Toast.LENGTH_SHORT).show();
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    /**
     * @return
     * @method
     * @description 送礼物动画
     * @date: 2018/11/23 11:49
     * @author: ljp
     */
    public void loadAnimation(URL url) {
        SVGAParser parser = new SVGAParser(activity);
        resetDownloader(parser);
        parser.parse(url, new SVGAParser.ParseCompletion() {
            @Override
            public void onComplete(@NotNull SVGAVideoEntity videoItem) {
                SVGADrawable drawable = new SVGADrawable(videoItem, requestDynamicItemWithSpannableText());
                svgImage.setVisibility(View.VISIBLE);
                svgImage.setImageDrawable(drawable);
                svgImage.setLoops(1);
                svgImage.startAnimation();
            }

            @Override
            public void onError() {
            }
        });
        svgImage.setCallback(new SVGACallback() {
            @Override
            public void onPause() {
            }

            @Override
            public void onFinished() {
                isSvg = false;
                svgImage.setVisibility(View.GONE);
                PopUtils.hidePopupWindow();
            }

            @Override
            public void onRepeat() {
            }

            @Override
            public void onStep(int frame, double percentage) {
            }
        });
    }

    /**
     * 你可以设置富文本到 ImageKey 相关的元素上
     * 富文本是会自动换行的，不要设置过长的文本
     *
     * @return
     */
    private SVGADynamicEntity requestDynamicItemWithSpannableText() {
        SVGADynamicEntity dynamicEntity = new SVGADynamicEntity();
        SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder("Pony 送了一打风油精给主播");
        spannableStringBuilder.setSpan(new ForegroundColorSpan(Color.YELLOW), 0, 4, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
        TextPaint textPaint = new TextPaint();
        textPaint.setColor(Color.WHITE);
        textPaint.setTextSize(28);
        dynamicEntity.setDynamicText(new StaticLayout(
                spannableStringBuilder,
                0,
                spannableStringBuilder.length(),
                textPaint,
                0,
                Layout.Alignment.ALIGN_CENTER,
                1.0f,
                0.0f,
                false
        ), "banner");
        dynamicEntity.setDynamicDrawer(new Function2<Canvas, Integer, Boolean>() {
            @Override
            public Boolean invoke(Canvas canvas, Integer frameIndex) {
                Paint aPaint = new Paint();
                aPaint.setColor(Color.WHITE);
                canvas.drawCircle(50, 54, frameIndex % 5, aPaint);
                return false;
            }
        }, "banner");
        return dynamicEntity;
    }

    /**
     * 设置下载器，这是一个可选的配置项。
     *
     * @param parser
     */
    private void resetDownloader(SVGAParser parser) {
        parser.setFileDownloader(new SVGAParser.FileDownloader() {
            @Override
            public void resume(final URL url, final Function1<? super InputStream, Unit> complete, final Function1<? super Exception, Unit> failure) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        OkHttpClient client = new OkHttpClient();
                        Request request = new Request.Builder().url(url).get().build();
                        try {
                            Response response = client.newCall(request).execute();
                            complete.invoke(response.body().byteStream());
                        } catch (IOException e) {
                            e.printStackTrace();
                            failure.invoke(e);
                        }
                    }
                }).start();
            }
        });
    }

    /**
     * @return
     * @method
     * @description 回复搭讪消息
     * @date: 2018/12/13 15:23
     * @author: ljp
     */
    private void sendReplyMessage() {
        MeInfoService.sendReplyMessage(token, deviceInfo, mySeleInfo.getId(), otherId).subscribe(result -> {
            Log.i(TAG, "sendReplyMessage: --------" + result.toString());
        }, throwable -> {
            Log.i(TAG, "sendReplyMessage: ---------" + throwable.toString());
        });
    }

}
